<template>
    <div>
        <DeviceSearch :query="query" :options="searchOpt" :search="handleSearch" :searchoverdue="handleSearchOverdue" :searchwilloverdue="handleSearchWillOverdue"
                      :exportByCompanyName="handleExportByName" @reset="handleReset" />
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                :delFunc="deleteDevice" :page-change="changePage" :editFunc="handleEdit" :row-class-name="rowClassName">
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
                    <el-button type="primary" @click="getAllOverdue">获取全部逾期设备</el-button>
                    <el-button type="primary" @click="getAllWillOverdue">获取全部即将逾期设备</el-button>
                    <el-button type="info" @click="exportTable">全部导出</el-button>
                </template>
            </TableCustom>
        </div>
      <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="900px" destroy-on-close
                 :close-on-click-modal="false" @close="closeDialog">
        <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" @submit="handleSubmit" />
      </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { Device } from '@/types/device';
import TableCustom from '@/components/table-custom.vue';
import DeviceSearch from '@/components/device-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import {
  getAllEquipments,
  getAllOverdueEquips,
  getAllWillOverdueEquips,
  deleteEquipment,
  getAllEquipmentsByCompanyName,
  getOverdueEquipmentsByCompanyName,
  getWillOverdueEquipsByCompanyName,
  exportAllEquipment,
  exportAll,
  insertEquip,
  updateEquip
} from "@/api/device";
import dayjs from "dayjs";

// 新增设备
const handleAdd = () => {
  rowData.value = {}; // 清空表单数据
  isEdit.value = false; // 设置为新增模式
  visible.value = true; // 打开弹窗
};

// 提交表单
const handleSubmit = async (formData: Device) => {
  try {
    if (isEdit.value) {
      // 编辑模式
      await updateEquip(formData);
      ElMessage.success('编辑成功');
    } else {
      // 新增模式
      await insertEquip(formData);
      ElMessage.success('新增成功');
    }
    closeDialog();
    getData(); // 重新获取数据
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败: ' + error.message);
  }
};


const getAllOverdue = async () => {
  try {
    const res = await getAllOverdueEquips();
    console.log('获取全部逾期设备的结果:', res);
    if (Array.isArray(res.data.data.data)) {
      tableData.value = res.data.data.data; // 更新表格数据
      page.total = res.data.data.data.length; // 更新总条数
    } else {
      console.error('返回的数据:', res);
      ElMessage.error('无逾期设备');
    }
  } catch (error) {
    console.error('获取全部逾期设备失败:', error);
    ElMessage.error('获取全部逾期设备失败: ' + error.message);
  }
};

const getAllWillOverdue = async () => {
  try {
    const res = await getAllWillOverdueEquips();
    console.log('获取全部即将逾期设备的结果:', res);
    if (Array.isArray(res.data.data.data)) {
      tableData.value = res.data.data.data; // 更新表格数据
      page.total = res.data.data.data.length; // 更新总条数
    } else {
      console.error('返回的数据:', res);
      ElMessage.error('无即将逾期设备');
    }
  } catch (error) {
    console.error('获取全部即将逾期设备失败:', error);
    ElMessage.error('获取全部即将逾期设备失败: ' + error.message);
  }
};


// 查询相关
const query = reactive({
   companyName: '',
});
const searchOpt = ref<FormOptionList[]>([
    { type: 'input', label: '单位名称：', prop: 'companyName' }
])
// 记录当前查询类型
const searchType = ref<'normal' | 'overdue' | 'willoverdue' >('normal');
const handleSearch = async () => {
  searchType.value = 'normal';
  try {
    console.log('查询的企业名称:', query.companyName);
    const res = await getAllEquipmentsByCompanyName(query.companyName);
    console.log('查询结果:', res);
    if (res.data && Array.isArray(res.data.data)) {
      tableData.value = res.data.data; // 更新表格数据
      page.total = res.data.data.length; // 更新总条数
    } else {
      console.error('接口返回的数据格式不正确:', res);
      ElMessage.error('数据格式不正确');
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败');
  }
};

const handleSearchOverdue = async () => {
  searchType.value = 'overdue';
  try {
    console.log('查询的企业名称:', query.companyName);
    const res = await getOverdueEquipmentsByCompanyName(query.companyName);
    console.log('查询结果:', res);
    if (Array.isArray(res.data.data.data)) {
      tableData.value = res.data.data.data; // 更新表格数据
      page.total = res.data.data.data.length; // 更新总条数
    } else {
      console.error('返回的数据:', res);
      ElMessage.error('无逾期设备');
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败: ' + error.message);
  }
};

const handleSearchWillOverdue = async () => {
  searchType.value = 'willoverdue';
  try {
    console.log('查询的企业名称:', query.companyName);
    const res = await getWillOverdueEquipsByCompanyName(query.companyName);
    console.log('查询结果:', res);
    if (Array.isArray(res.data.data.data)) {
      tableData.value = res.data.data.data; // 更新表格数据
      page.total = res.data.data.data.length; // 更新总条数
    } else {
      console.error('返回的数据:', res);
      ElMessage.error('无即将逾期设备');
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败: ' + error.message);
  }
};

const handleReset = () => {
  query.companyName = ''; // 清空查询条件
  getData(); // 恢复表格数据
};

// 导出设备表格
const exportTable = async () => {
  try {
    const response = await exportAll( );
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `全部设备列表.xlsx`);
    document.body.appendChild(link);
    link.click(); // 触发下载
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + error.message);
  }
};

const handleExportByName = async () => {
  try {
    if (!query.companyName) {
      ElMessage.warning('请输入单位名称');
      return;
    }
    const response = await exportAllEquipment(query.companyName);

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${query.companyName}_设备列表.xlsx`);
    document.body.appendChild(link);
    link.click(); // 触发下载
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败: ' + error.message);
  }
};


// 表格相关
let columns = ref([
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'companyName', label: '单位名称' },
    { prop: 'type', label: '特种设备种类' },
    { prop: 'ename', label: '设备名称' },
    { prop: 'ecode', label: '设备代码' },
    { prop: 'registrationNumber', label: '使用登记证编号' },
    { prop: 'version', label: '设备型号规格' },
    { prop: 'usingPlace', label: '使用地点' },
    { prop: 'productNumber', label: '产品编号' },
    { prop: 'commissioningDate', label: '投入使用日期' },
    { prop: 'inspectionDate', label: '检验日期' },
    { prop: 'nextInspectionDate', label: '下次检验日期' },
    { prop: 'operator', label: '操作', width: 200 },
])
const page = reactive({
    index: 1,
    size: 10,
    total: 0,
})
const tableData = ref<Device[]>([]);

const getData = async () => {
  try {
    const res = await getAllEquipments();
    console.log('接口返回数据:', res);
    if (res.data && Array.isArray(res.data.data)) {
      // 格式化时间字段
      tableData.value = res.data.data.map(item => ({
        ...item
      }));
      page.total = res.data.data.length; // 更新总条数
    } else {
      console.error('接口返回的数据格式不正确:', res);
      ElMessage.error('数据格式不正确');
    }
  } catch (error) {
    console.error('接口调用失败:', error);
    ElMessage.error('获取数据失败');
  }
};

// 在组件挂载时调用 getData
onMounted(() => {
  getData();
});


const changePage = (val: number) => {
  page.index = val;
  if (query.companyName) {
    if (searchType.value === 'normal') {
      handleSearch();
    } else if (searchType.value === 'overdue') {
      handleSearchOverdue();
    }else if (searchType.value === 'willoverdue'){
      handleSearchWillOverdue();
    }
  } else {
    getData(); // 如果没有查询条件，加载所有数据
  }
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '150px',
    span: 12,
    list: [
        { type: 'input', label: '单位名称', prop: 'companyName', required: true },
        { type: 'input', label: '特种设备种类', prop: 'type', required: true },
        { type: 'input', label: '设备名称', prop: 'ename', required: true },
        { type: 'input', label: '设备代码', prop: 'ecode', required: true },
        { type: 'input', label: '使用登记证编号', prop: 'registrationNumber', required: true },
        { type: 'input', label: '设备型号规格', prop: 'version', required: true },
        { type: 'input', label: '使用地点', prop: 'usingPlace', required: true },
        { type: 'input', label: '产品编号', prop: 'productNumber', required: true },
        { type: 'input', label: '投入使用日期', prop: 'commissioningDate', required: true },
        { type: 'input', label: '检验日期', prop: 'inspectionDate', required: true },
        { type: 'input', label: '下次检验日期', prop: 'nextInspectionDate', required: true },
    ]
})
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = (row: Device) => {
    rowData.value = { ...row };
    isEdit.value = true;
    visible.value = true;
};
const updateData = () => {
    closeDialog();
    getData();
};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});
const handleView = (row: Device) => {
    viewData.value.row = { ...row }
    viewData.value.list = [
        {
            prop: 'id',
            label: '用户ID',
        },
        {
            prop: 'name',
            label: '用户名',
        },
        {
            prop: 'password',
            label: '密码',
        },
        {
            prop: 'email',
            label: '邮箱',
        },
        {
            prop: 'phone',
            label: '电话',
        },
        {
            prop: 'role',
            label: '角色',
        },
        {
            prop: 'date',
            label: '注册日期',
        },
    ]
    visible1.value = true;
};

// 删除相关
const deleteDevice = async (row: Device) => {
  try {
    console.log('删除的设备 ID:', row.id);
    await deleteEquipment(row.id);
    ElMessage.success('删除成功');
    getData(); // 删除成功后重新获取数据
  } catch (error) {
    console.error('删除失败:');
  }
}

// 判断设备是否逾期
const isOverdue = (nextInspectionDate: string) => {
  const today = dayjs().format('YYYY-MM-DD'); // 获取当前日期
  return dayjs(nextInspectionDate).isBefore(today); // 判断是否早于当前日期
};

// 动态设置行样式
const rowClassName = ({ row }: { row: Device }) => {
  if (isOverdue(row.nextInspectionDate)) {
    return 'overdue-row'; // 返回逾期行的样式类名
  }
  return '';
};


</script>

<style scoped>
/* 逾期设备的行样式 */
:deep(.el-table .overdue-row) {
  background-color: #ffcccc;
}
</style>